package org.backend.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.backend.pojo.entity.Address;
import org.backend.repository.AddressRepository;
import org.backend.service.AddressService;
import org.backend.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressRepository addressRepository;

    @Override
    @Transactional
    // todo 判断不易读
    public String add(Address address) {
        if (address.getIsDefault()) {
            addressRepository.updateDefault();
        }
        int row;
        if (address.getId() != null) {
            row = addressRepository.update(address);
            if (row == 0) {
                throw new IllegalArgumentException("修改失败");
            }
            return "修改成功";
        }
        if (address.getName() != null && !address.getName().isEmpty() &&
                address.getCity() != null && !address.getCity().isEmpty() &&
                address.getProvince() != null && !address.getProvince().isEmpty() &&
                address.getDistrict() != null && !address.getDistrict().isEmpty()
        ) {
            row = addressRepository.add(address);
            if (row == 0) {
                throw new IllegalArgumentException("添加失败");
            }
            return "修改成功";
        }
        return null;
    }

    @Override
    public List<Address> getAddress(String openid, Integer userId) {
        // 地址信息允许为空
        return addressRepository.getAddress(openid, userId);
    }

    @Override
    public Address getAddressById(Integer id) {
        return addressRepository.getAddressById(id);
    }

    @Override
    public ApiResponse<String> setDefaultAddress(Integer id) {
        addressRepository.updateDefault();
        Address address = new Address();
        address.setId(id);
        address.setIsDefault(true);
        addressRepository.update(address);
        return ApiResponse.success("设置默认地址成功");
    }

    @Override
    public Address getDefaultAddress(String openid, Integer userId) {
        Address address = addressRepository.getDefaultAddress(openid, userId);
        if (address == null) {
            throw new IllegalArgumentException("获取默认地址失败");
        }
        return address;
    }
}
